<?php
/**
 * Created by veema.
 * Function:赛艇相关计算类
 * Date: 20/9/4
 * Time: 14:00
 */

namespace app\api\controller;

use app\common\service\Exception;
use app\common\service\QueueService;
use think\Cache;
use think\Db;
use think\Error;
use think\exception\ErrorException;
use think\Request;
use app\admin\model\Device as DeviceModel;
use app\admin\model\DeviceSensor as DeviceSensorModel;
use think\Log;
use think\cache\driver\Redis as myRedis;

class Yacht extends Base
{

    //存放船和坐标临时位置
    public $temp_location_data = [];
    public $temp_location_data_last = [];//上一次位置
    public $temp_record = [];//船只路程记录临时表
    public $temp_record_last = [];//上次船只路程记录临时表
    public $match_turns_rounds_info = [];//本赛次轮次组次记录
    //------------------------------------------倒计时相关-------------------------------------------//
    private $temp_all_countdown = 300;//倒计时
    private $temp_start_time = 0;//倒计时结束时间
    private $time_now = 0;//现在时间
    //------------------------------------------时限相关-------------------------------------------//
    public $match_zhong_limit = 15 * 60;//终点时限
    public $match_first_zhong_limit = 0;//第一艘船到达终点时间+15min
    public $redis;
    //==========================================比赛信息相关=========
    public $turns_rounds_info = [];//赛次信息
    public $match_info = [];//比赛信息
    //==========================================比赛信息相关=========
    public $turns_info = [];//赛次信息
    public $rounds_info = [];//组次信息
    public $groups_info = [];//组别信息

    public function __construct()
    {
        $this->temp_all_countdown = Db::table('up__match_config')->where('param_name', 'ready_time')->value('param_value');
        $this->rounds_info        = Db::table('up__match_rounds')->column('mr_id,mr_name');
        $this->turns_info         = Db::table('up__match_turns')->column('mt_id,mt_name');
        $this->groups_info        = Db::table('up_match_group')->column('mg_id,mg_name');
        $this->redis              = new myRedis();
    }

    /**
     * 获取比赛基础信息
     * @param $match_id 比赛id
     */
    public function race_info()
    {
        try {
            $match_id = input('match_id');
            if (!$match_id) {
                return json(array('status' => 100, 'msg' => '比赛id不能为空'));
            }
            $match_info = Db::table('up_match')
                ->where('match_id', $match_id)
                ->where('match_init', 2)->find();
            if (!$match_info) {
                return json(array('status' => 100, 'msg' => '该比赛还未开始或者人数过少不能初始化'));
            }
            $data                     = $this->_match_info($match_id);
            $data["ready_time"]       = $this->temp_all_countdown;
            $data["match_saidao_num"] = $match_info['match_saidao_num'];
            return json(array('status' => 200, 'msg' => 'success', 'data' => $data));
        } catch (\Exception $e) {
            return json(array('status' => 100, 'msg' => $e->getMessage() . '行：' . $e->getLine()));
        }
    }

    public function _match_info($match_id)
    {
        $data = [];
        // 比赛包含的赛事组别信息
        $data['group_types'] = Db::table('up_match_apply_group ag')
            ->join('up_match_group g', 'ag.mag_group_id=g.mg_id', 'LEFT')
            ->where('mag_match_id', $match_id)->field('g.mg_id as id,g.mg_name as name')->select();
        // 比赛包含的轮次信息
        $data["turns"] = Db::table("up__match_turns_rounds")->alias('tr')
            ->join('up__match_turns t', 't.mt_id=tr.mt_id', "LEFT")
            ->distinct('tr.mt_id')
            ->field('tr.mt_id as id,t.mt_name as name')
            ->where('match_id', $match_id)->select();
        // 比赛包含的组次信息
        $data["rounds"] = Db::table("up__match_turns_rounds")->alias('tr')
            ->join('up__match_rounds t', 't.mr_id=tr.mr_id', "LEFT")
            ->distinct('tr.mr_id')
            ->field('tr.mr_id as id ,t.mr_name as name')
            ->where('match_id', $match_id)->select();
        // 比赛包含的参赛赛艇船型
        $data["yacht_types"]    = Db::table("up__match_turns_rounds")
            ->distinct('ma_boat_type')
            ->where('match_id', $match_id)->column('ma_boat_type');
        $data["race_distances"] = Db::table("up__match_turns_rounds")
            ->distinct('ma_distance')
            ->where('match_id', $match_id)->column('ma_distance');
        return $data;
    }

    /**
     * 设置比赛基础信息
     * @param $match_id 比赛id
     */
    public function set_race_info()
    {
        try {

            $match_id = input('match_id');
            if (!$match_id) {
                return json(array('status' => 100, 'msg' => '比赛id不能为空'));
            }

            $data = input('sets');
            $data = json_decode($data, true);

            if (!key_exists('group_type', $data)) {
                return json(array('status' => 100, 'msg' => '组别类型不能为空'));
            }
            if (!key_exists('turn', $data)) {
                return json(array('status' => 100, 'msg' => '轮次不能为空'));
            }
            if (!key_exists('round', $data)) {
                return json(array('status' => 100, 'msg' => '组次不能为空'));
            }
            if (!key_exists('yacht_type', $data)) {
                return json(array('status' => 100, 'msg' => '赛艇类型不能为空'));
            }
            if (!key_exists('race_distance', $data)) {
                return json(array('status' => 100, 'msg' => '赛道长度不能为空'));
            }

            // 比赛包含的赛事组别信息
            $data_new['turns_rounds_info'] = Db::table('up__match_turns_rounds')
                ->where('match_id', $match_id)
                ->where('ma_group', $data['group_type'])
                ->where('ma_boat_type', $data['yacht_type'])
                ->where('ma_distance', $data['race_distance'])
                ->where('mr_id', $data['round'])
                ->where('mt_id', $data['turn'])
                //->where('type', 'in', [0, 1, 3])
                ->find();

            if (!is_array($data_new['turns_rounds_info'])) {
                $turns_rounds_info = [];
            } else {
                //去match_info表查询相关选手
                $data_new['all_user_info'] = Db::table('up_match_apply_info')
                    ->alias('i')
                    ->join('up_club c', 'c.club_id=i.ma_club_id', "LEFT")
                    ->where([
                        'ma_match_id'   => $data_new['turns_rounds_info']['match_id'],
                        'ma_group'      => $data_new['turns_rounds_info']['ma_group'],
                        'ma_boat_type'  => $data_new['turns_rounds_info']['ma_boat_type'],
                        'ma_distance'   => $data_new['turns_rounds_info']['ma_distance'],
                        'ma_turns_id'   => $data_new['turns_rounds_info']['mt_id'],
                        'ma_rounds_id'  => $data_new['turns_rounds_info']['mr_id'],
                        'ma_match_cate' => 2,
                        'ma_role'       => 1,//必须是船长
                        //'ma_baodao_status'=>2
                    ])
                    ->field("ma_user_id as user_id,concat('boat_',`ma_user_id`) as sensor_id,i.ma_dao_num as track_num,i.ma_team_name,c.club_name,c.club_image,i.ma_color as color")->select();
            }
            return json(array('status' => 200, 'msg' => 'success', 'data' => $data_new));
        } catch (\Exception $e) {
            return json(array('status' => 100, 'msg' => $e->getMessage() . '行：' . $e->getLine()));
        }
    }

    /**
     * 查询某个用户正在进行中的比赛
     * @param $match_id 比赛id
     * @param $user_id 用户id
     */
    public function race_now()
    {
        try {

            $match_id = input('match_id');
            $user_id  = input('user_id');
            $all_time = [];

            if (!$match_id) {
                return json(array('status' => 100, 'msg' => '比赛id不能为空'));
            }
            if (!$user_id) {
                return json(array('status' => 100, 'msg' => '用户id不能为空'));
            }
            //查询用户现在所属比赛
            $user_info = json_decode($this->redis->get('ma_match_id' . $match_id . 'ma_user_id' . $user_id), true);
//            $user_info = Db::table('up_match_apply_info')
//                ->where([
//                    'ma_match_id' => $match_id,
//                    'ma_user_id'  => $user_id,
//                ])->find();
            if (!$user_info) {
                return json(array('status' => 100, 'msg' => '该用户没有相关比赛'));
            }

            $res_turns_rounds  = json_decode($this->redis->get('up__match_turns_rounds_info'), true);
            $turns_rounds_info = json_decode($this->redis->get('turns_rounds_info'), true);
            if (!$turns_rounds_info) {
                // 比赛包含的赛事组别信息
                $turns_rounds_info = Db::table('up__match_turns_rounds')
                    ->alias('tr')
                    //->join('up__match_turns t', 'tr.mt_id=t.mt_id', "LEFT")
                    //->join('up__match_rounds r', 'tr.mr_id=r.mr_id', "LEFT")
                    //->join('up_match_group g', 'g.mg_id=tr.ma_group', "LEFT")
                    ->where('tr.match_id', $user_info['ma_match_id'])
                    ->where('tr.mt_id', $user_info['ma_turns_id'])
                    ->where('tr.mr_id', $user_info['ma_rounds_id'])
                    ->where('tr.ma_group', $user_info['ma_group'])
                    ->where('tr.ma_boat_type', $user_info['ma_boat_type'])
                    ->where('tr.ma_distance', $user_info['ma_distance'])
                    ->field('tr.*')
                    ->find();
                //,t.mt_name,r.mr_name,g.mg_name
                if (!$turns_rounds_info) {
                    return json(array('status' => 100, 'msg' => '没有相关比赛'));
                } else {
                    $turns_rounds_info['mg_name'] = $this->groups_info[$turns_rounds_info['ma_group']];
                    $turns_rounds_info['mt_name'] = $this->turns_info[$turns_rounds_info['mt_id']];
                    $turns_rounds_info['mr_name'] = $this->rounds_info[$turns_rounds_info['mr_id']];
                    $this->redis->set('turns_rounds_info', json_encode($turns_rounds_info));
                    //Cache::set('turns_rounds_info', $turns_rounds_info, 3600);
                }
            } else {
                if (!(($turns_rounds_info['match_id'] == $user_info['ma_match_id']) &&
                    ($turns_rounds_info['mt_id'] == $user_info['ma_turns_id']) &&
                    ($turns_rounds_info['mr_id'] == $user_info['ma_rounds_id']) &&
                    ($turns_rounds_info['ma_group'] == $user_info['ma_group']) &&
                    ($turns_rounds_info['ma_boat_type'] == $user_info['ma_boat_type']) &&
                    ($turns_rounds_info['ma_distance'] == $user_info['ma_distance'])
                )) {
                    // 比赛包含的赛事组别信息
                    $turns_rounds_info = Db::table('up__match_turns_rounds')
                        ->alias('tr')
                        /*                        ->join('up__match_turns t', 'tr.mt_id=t.mt_id', "LEFT")
                                                ->join('up__match_rounds r', 'tr.mr_id=r.mr_id', "LEFT")
                                                ->join('up_match_group g', 'g.mg_id=tr.ma_group', "LEFT")*/
                        ->where('tr.match_id', $user_info['ma_match_id'])
                        ->where('tr.mt_id', $user_info['ma_turns_id'])
                        ->where('tr.mr_id', $user_info['ma_rounds_id'])
                        ->where('tr.ma_group', $user_info['ma_group'])
                        ->where('tr.ma_boat_type', $user_info['ma_boat_type'])
                        ->where('tr.ma_distance', $user_info['ma_distance'])
                        ->field('tr.*')
                        ->find();
                    if (!$turns_rounds_info) {
                        return json(array('status' => 100, 'msg' => '没有相关比赛'));
                    } else {
                        $turns_rounds_info['mg_name'] = $this->groups_info[$turns_rounds_info['ma_group']];
                        $turns_rounds_info['mt_name'] = $this->turns_info[$turns_rounds_info['mt_id']];
                        $turns_rounds_info['mr_name'] = $this->rounds_info[$turns_rounds_info['mr_id']];
                        $this->redis->set('turns_rounds_info', json_encode($turns_rounds_info));
                        //Cache::set('turns_rounds_info', $turns_rounds_info, 3600);
                    }
                } else {
                    if(count($res_turns_rounds)>0){
                        $turns_rounds_info['type']       = $res_turns_rounds['type'];
                        $turns_rounds_info['start_time'] = $res_turns_rounds['start_time'];
                        $turns_rounds_info['end_time']   = $res_turns_rounds['end_time'];
                        $this->redis->set('turns_rounds_info', json_encode($turns_rounds_info));
                    }
                }
            }

            $turns_rounds_info['track_num'] = $user_info['ma_dao_num'];
            $time                           = time();
            $time_scope                     = $time - 1;
            $boat_calculate_data            = [];
            $boat_calculate_data            = json_decode($this->redis->get('up__match_datas_yacht'), true);
            //dump($boat_calculate_data);die;
            /*$boat_calculate_data = Db::table('up__match_datas_yacht')
                ->where(['match_turns_rounds_id' => $turns_rounds_info['id']])
                ->where('time', '>', $time_scope)
                ->where('time', '<=', $time)
                ->order('time desc')->value('data');*/
            if ($boat_calculate_data == NULL || $boat_calculate_data == "" || $boat_calculate_data == []) {
                /*$user_info = Db::table('up__match_yacht_record')
                    ->where([
                        'match_turns_rounds_id' => $turns_rounds_info['id'],
                        'user_id'               => $user_id,
                        'type'                  => 2,
                    ])->find();*/
                //if ($user_info) {
                //    $boat_calculate_data = $user_info;
                //} else {
                $boat_calculate_data = [
                    //帆船参数计算结果
                    "sensor_id"              => 'boat_' . $user_id, //设备id
                    "user_id"                => $user_id,
                    "ranking"                => 1, //排名
                    "temp_score"             => 1, //排名
                    "distance"               => 0, //已行进距离
                    "speed"                  => 0, //速度
                    "arrive_time"            => 0, //到达时间
                    "accumulated_time"       => 0,//累计用时
                    "track_num"              => $turns_rounds_info['track_num'], //赛道
                    "arrive_time_first"      => 0, //到达时间
                    "to_first_distance"      => 0, //距第一名距离
                    "five_hundred_time"      => 0, //到达500米时间
                    "five_hundred_consuming" => 0,//500米用了多久时间
                    'average_fh_start_time'  => 0,
                    'average_speed'          => 0,
                ];
                //}
            } else {
                if (!is_array($boat_calculate_data)) {
                    $boat_calculate_data = json_decode($boat_calculate_data, true);
                }
                foreach ($boat_calculate_data as $k => $v) {
                    if ($v['user_id'] == $user_id) {
                        $boat_calculate_data = $v;
                        break;
                    }
                }
            }
            $data = [
                "turns_rounds_info"   => $turns_rounds_info, //比赛轮次id
                "time"                => $time, // 时间戳
                "cal_time"            => $all_time,
                "ready_time"          => $this->temp_all_countdown,//偏移时间
                "boat_calculate_data" => $boat_calculate_data, //船只参数计算结果
            ];

            return json(array('status' => 200, 'msg' => 'success', 'data' => $data));
        } catch (\Exception $e) {
            return json(array('status' => 100, 'msg' => $e->getMessage() . '行：' . $e->getLine()));
        }
    }

    /**
     * 开始比赛
     * @param $match_turns_rounds_id 比赛轮次赛次组次id
     * @param $user_id 裁判长id  必须
     */
    public function race_start()
    {
        try {
            echo 4;die;
            $match_turns_rounds_id = input('match_turns_rounds_id');
            $user_id               = input('user_id');
            if (!$match_turns_rounds_id) {
                return json(array('status' => 100, 'msg' => '比赛轮次赛次组次id不能为空'));
            }
            //裁判权限
            $match_turns_info = Db::table("up__match_turns_rounds")->alias('d')->join("up_match m", "m.match_id=d.match_id")->field('m.match_zong_user_id,d.*')->where('d.id', $match_turns_rounds_id)->find();
            if ($match_turns_info['match_zong_user_id'] != $user_id) {
                return json(array('status' => 100, 'msg' => "此用户没有权限开始比赛！"));
            }

            //开始比赛
            $up__match_turns_rounds = Db::table('up__match_turns_rounds')
                ->where('id', $match_turns_rounds_id)
                ->where('type', 'in', [0, 1, 3])
                ->find();

            if (!$up__match_turns_rounds) {
                return json(array('status' => 100, 'msg' => '该比赛已经完成，不能重新开始'));
            }
            //查询是否可以初始化
            $ing_turns_rounds = Db::table('up__match_turns_rounds')
                ->where([
                    'match_id'     => $match_turns_info['match_id'],
                    'ma_group'     => $match_turns_info['ma_group'],
                    'ma_boat_type' => $match_turns_info['ma_boat_type'],
                    'ma_distance'  => $match_turns_info['ma_distance']
                ])
                ->where('id', '<', $match_turns_rounds_id)
                ->where('type', '<>', 2)
                ->order('id desc')
                ->find();
            if ($ing_turns_rounds) {
                return json(array('status' => 100, 'msg' => '请按照晋级规则依次进行比赛'));
            }
            // 查询是否初始化用户
            $data = Db::table('up__match_yacht_record')
                ->where('match_turns_rounds_id', $match_turns_rounds_id)
                ->find();
            if (!is_array($data)) {

                //去match_info表查询相关选手
                $user_list = Db::table('up_match_apply_info')->where([
                    'ma_match_id'   => $match_turns_info['match_id'],
                    'ma_group'      => $match_turns_info['ma_group'],
                    'ma_boat_type'  => $match_turns_info['ma_boat_type'],
                    'ma_distance'   => $match_turns_info['ma_distance'],
                    'ma_turns_id'   => $match_turns_info['mt_id'],
                    'ma_rounds_id'  => $match_turns_info['mr_id'],
                    'ma_match_cate' => 2,
                    'ma_role'       => 1,
                    //'ma_baodao_status'=>2
                ])->field("ma_user_id as user_id,concat('boat_',`ma_user_id`) as sensor_id,ma_dao_num as track_num")->select();
                if (count($user_list) == 0) {
                    throw new Exception('请先对要进行比赛的用户进行分组,抽签', 4);
                }
                $rank = 1;
                foreach ($user_list as $k => $v) {
                    $data_record = [
                        'match_turns_rounds_id'  => $match_turns_rounds_id,
                        'sensor_id'              => $v['sensor_id'],
                        'user_id'                => $v['user_id'],
                        'distance'               => 0,
                        'ranking'                => $rank,
                        'temp_score'             => $rank,
                        'lat'                    => '',
                        'lon'                    => '',
                        'speed'                  => 0,
                        'time'                   => '',
                        'arrive_time'            => '',
                        "accumulated_time"       => '',//累计用时
                        'type'                   => 1,
                        'track_num'              => $v['track_num'],
                        'arrive_time_first'      => '',
                        'to_first_distance'      => 0,
                        'five_hundred_time'      => 0,
                        'five_hundred_consuming' => 0,
                        'average_fh_start_time'  => 0,
                        'average_speed'          => 0,
                    ];

                    $rank++;

                    $record_id                          = Db::table('up__match_yacht_record')->insertGetId($data_record);
                    $data['id']                         = $record_id;
                    $this->temp_record[$v['sensor_id']] = $data_record;
                }
                //return json(array('status' => 100, 'msg' => '请先对要进行比赛的用户进行分组,抽签'));
            }

            $start_time = microtime(true);
            Db::table("up__match_turns_rounds")->where('id', $match_turns_rounds_id)->update([
                'start_time' => $start_time,
                'end_time'   => null,
                'type'       => 1
            ]);
            $res_turns_rounds = Db::table("up__match_turns_rounds")->where('id', $match_turns_rounds_id)->find();
            $this->redis->set('up__match_turns_rounds_info', json_encode($res_turns_rounds));
            dump($res_turns_rounds);die;
            $this->redis->set('up__match_datas_yacht', '');
            //初始化记录表
            $this->record_table($match_turns_rounds_id);
            //开启定时数据计算
            (new QueueService())->startYachtMatch($match_turns_rounds_id);

            return json(array('status' => 200, 'msg' => "比赛开始", "data" => ['start_time' => $start_time]));
        } catch (\think\Exception $e) {
            return json(array('status' => 100, 'msg' => "比赛开始失败" . $e->getMessage()));
        }
    }

    /**
     * 终止比赛
     * @param $match_turns_rounds_id 比赛轮次赛次组次id
     * @param $user_id 裁判长id  必须
     */
    public function race_stop()
    {
        try {
            $match_turns_rounds_id = input('match_turns_rounds_id');
            if (!$match_turns_rounds_id) {
                return json(array('status' => 100, 'msg' => '比赛轮次赛次组次id不能为空'));
            }
            $user_id = input('user_id');
            //裁判权限
            $match_turns_infos = Db::table("up__match_turns_rounds")
                ->alias('d')
                ->join("up_match m", "m.match_id=d.match_id")
                ->field('m.match_zong_user_id,d.*')
                ->where('d.id', $match_turns_rounds_id)->find();
            if ($match_turns_infos['match_zong_user_id'] != $user_id) {
                return json(array('status' => 100, 'msg' => "此用户没有权限终止比赛！"));
            }

            // 查询是否初始化用户
            $data = Db::table('up__match_yacht_record')
                ->where('match_turns_rounds_id', $match_turns_rounds_id)
                ->find();
            if (!is_array($data)) {
                return json(array('status' => 100, 'msg' => '请先对要进行比赛的用户进行分组,抽签'));
            }

            //终止比赛
            $up__match_turns_rounds = Db::table('up__match_turns_rounds')
                ->where('id', $match_turns_rounds_id)
                ->where('type', '=', 1)
                ->find();

            if (!$up__match_turns_rounds) {
                return json(array('status' => 100, 'msg' => '该比赛未在进行中状态，不能操作'));
            }

            Db::table("up__match_turns_rounds")->where('id', $match_turns_rounds_id)->update([
                'end_time' => microtime(true),
                'type'     => 3
            ]);
            $res_turns_rounds = Db::table("up__match_turns_rounds")->where('id', $match_turns_rounds_id)->find();
            $this->redis->set('up__match_turns_rounds_info', json_encode($res_turns_rounds));
            $this->redis->set('up__match_datas_yacht', '');
            return json(array('status' => 200, 'msg' => "比赛终止成功"));
        } catch (\think\Exception $e) {
            return json(array('status' => 100, 'msg' => "比赛终止失败" . $e->getMessage()));
        }
    }

    /**
     * 创建record记录
     * @param $match_turns_rounds_id 比赛轮次id  必须
     */
    public function record_table($match_turns_rounds_id)
    {
        //倒计时为0的时间
        //temp_all_countdown = 300;//倒计时
        //temp_start_time = 0;//倒计时结束时间
        $time                  = microtime(true);
        $this->temp_start_time = $time + $this->temp_all_countdown;

        $this->turns_rounds_info = $up__match_turns_rounds = Db::table('up__match_turns_rounds')
            ->where('id', $match_turns_rounds_id)
            ->where('type', 'in', [0, 1, 3])
            ->find();

        $this->temp_record = [];
        $all_user_record   = Db::table('up__match_yacht_record')
            ->where('match_turns_rounds_id', $match_turns_rounds_id)->select();
        $rank              = 1;

        foreach ($all_user_record as $k => $v) {
            $data = [
                'match_turns_rounds_id'  => $match_turns_rounds_id,
                'sensor_id'              => $v['sensor_id'],
                'user_id'                => $v['user_id'],
                'distance'               => 0,
                'ranking'                => $rank,
                'temp_score'             => $rank,
                'lat'                    => '',
                'lon'                    => '',
                'speed'                  => 0,
                'time'                   => '',
                'arrive_time'            => '',
                "accumulated_time"       => '',//累计用时
                'type'                   => 1,
                'track_num'              => $v['track_num'],
                'arrive_time_first'      => '',
                'to_first_distance'      => 0,
                'five_hundred_time'      => 0,
                'five_hundred_consuming' => 0,
                'average_fh_start_time'  => $time,
                'average_speed'          => 0,
            ];

            $rank++;

            $record_id                          = Db::table('up__match_yacht_record')->where('id', $v['id'])->update($data);
            $data['id']                         = $v['id'];
            $this->temp_record[$v['sensor_id']] = $data;
        }

        //获取所有设备绑定关系
        $yacht_sensor_id_arr = Db::table('up__match_yacht_record')->where('match_turns_rounds_id', $match_turns_rounds_id)->column('sensor_id');
        $this->redis->set('yacht_sensor_id_arr', json_encode($yacht_sensor_id_arr));
        //$this->temp_record_last = $this->temp_record;
        $this->match_turns_rounds_info = Db::table('up__match_turns_rounds')->where('id', $match_turns_rounds_id)->find();
        $this->match_info              = Db::table('up_match')->where('match_id', $this->match_turns_rounds_info['match_id'])->find();
        return $this->temp_record;
    }

    /**
     * 定时计算赛艇比赛信息
     * @param $match_turns_rounds_id 赛艇赛次id
     */
    public function calculateDatas($match_turns_rounds_id)
    {
        $flag = 0;
        if (!$match_turns_rounds_id) {
            return json(array('status' => 100, 'msg' => "赛次id不能为空"));
        }
        if (count($this->temp_record) < 1) {
            $this->record_table($match_turns_rounds_id);
        }
        //获取所有设备绑定关系
        $yacht_sensor_id_arr = json_decode($this->redis->get('yacht_sensor_id_arr'), true);
        //Db::table('up__match_yacht_record')->where('match_turns_rounds_id', $match_turns_rounds_id)->column('sensor_id');

        //快照时间点
        $time = time();
        //$this->time_now     = $time;
        $time_pre           = $time - 2;
        $map['create_time'] = ['>', $time_pre];
        $map['create_time'] = ['<=', $time];
//        $origin_data        = Db::table('up__match_origin')
//            ->distinct('sensor_id')
//            ->where('create_time', '>', $time_pre)
//            ->where('create_time', '<=', $time)
//            ->order('id desc')
//            ->column('sensor_id,lat,lon', 'sensor_id');
        $data_boat   = [];
        $data_sensor = [];
        //更新各个点和船只坐标缓存
        foreach ($yacht_sensor_id_arr as $k => $v) {
            if (strstr($v, 'boat_')) {
                $data_boat[$v]                = json_decode($this->redis->get($v), true);
                $this->temp_record[$v]['lat'] = $data_boat[$v]['lat'];
                $this->temp_record[$v]['lon'] = $data_boat[$v]['lon'];
                /* if (array_key_exists($v, $origin_data)) {
                     $data_boat[$v]                = $origin_data[$v];
                     $this->temp_record[$v]['lat'] = $origin_data[$v]['lat'];
                     $this->temp_record[$v]['lon'] = $origin_data[$v]['lon'];
                 }*/
            }
        }
        $step_data = $data_boat;
//        //生成快照
//        Db::table('up__match_step_yacht')->insert([
//            'match_turns_rounds_id' => $match_turns_rounds_id,
//            'time'                  => $time,
//            'data'                  => json_encode($step_data)
//        ]);
        //获取船只上一时刻和现在时刻的位置快照
        if ($this->temp_record_last == []) {
            $this->temp_record_last = $this->temp_record;
        }
        //如果倒计时结束则计算
        if ($time > $this->temp_start_time) {
            //开始循环计算
            foreach ($this->temp_record as $k => $v) {
                if (!$v['arrive_time']) {
                    $point_now                         = ['lat' => $v['lat'], 'lon' => $v['lon']];
                    $point_last                        = ['lat' => $this->temp_record_last[$k]['lat'], 'lon' => $this->temp_record_last[$k]['lon']];
                    $distance                          = $this->getDistance($point_now, $point_last);
                    $speed                             = $distance;
                    $all_distance                      = $this->temp_record_last[$k]['distance'] + $distance;
                    $this->temp_record[$k]['speed']    = $speed;
                    $this->temp_record[$k]['distance'] = $all_distance;
                    if ($all_distance >= $this->match_turns_rounds_info['ma_distance']) {
                        $this->temp_record[$k]['arrive_time']            = $time;
                        $this->temp_record[$k]['accumulated_time']       = $time - $this->match_turns_rounds_info['start_time'];
                        $this->temp_record[$k]['type']                   = 2;
                        $this->temp_record[$k]['distance']               = $this->match_turns_rounds_info['ma_distance'];
                        $this->temp_record[$k]['five_hundred_consuming'] = $this->temp_record[$k]['arrive_time'] - $v['five_hundred_time'];
                    }
                    if ((($this->match_turns_rounds_info['ma_distance'] - $all_distance) <= 500)
                        && (($this->match_turns_rounds_info['ma_distance'] - $this->temp_record_last[$k]['distance']) >= 500)) {
                        $this->temp_record[$k]['five_hundred_time'] = $time;
                    }
                    //计算500米均速
                    if ($this->match_turns_rounds_info['ma_distance'] == 500 || $this->temp_record[$k]['distance'] <= 500) {
                        $this->temp_record[$k]['average_speed'] = $speed * 3.6;
                    } else {
                        if (
                            ($this->temp_record_last[$k]['distance'] <= 500) && ($this->temp_record[$k]['distance'] >= 500)
                            ||
                            ($this->temp_record_last[$k]['distance'] <= 1000) && ($this->temp_record[$k]['distance'] >= 1000)
                            ||
                            ($this->temp_record_last[$k]['distance'] <= 1500) && ($this->temp_record[$k]['distance'] >= 1500)
                        ) {
                            $fhundred_time                                  = $time - $this->temp_record_last[$k]['average_fh_start_time'];
                            $this->temp_record[$k]['average_speed']         = (500 / $fhundred_time) * 3.6;
                            $this->temp_record[$k]['average_fh_start_time'] = $time;
                        } else {
                            $this->temp_record[$k]['average_speed'] = $this->temp_record_last[$k]['average_speed'];
                        }
                    }
                }
            }
            //循环更新到record表
            foreach ($this->temp_record as $k => $v) {
                Db::table('up__match_yacht_record')->where('id', $v['id'])->update($v);
            }
            //获取比赛排名
            $data_rank_temp = [];
            $match_rank     = Db::table('up__match_yacht_record')->where([
                'match_turns_rounds_id' => $match_turns_rounds_id,
                'type'                  => 2
            ])->order('arrive_time asc')->select();
            //先计算完成比赛的排序
            $temp_first_time     = 0;//第一名到达时间
            $temp_first_distance = 0;//第一名距离
            foreach ($match_rank as $k => $v) {
                $this->temp_record[$v['sensor_id']]['ranking']    = $k + 1;
                $this->temp_record[$v['sensor_id']]['temp_score'] = $k + 1;
                if ($k == 0) {
                    $temp_first_time                                         = $this->temp_record[$v['sensor_id']]['arrive_time'];
                    $this->temp_record[$v['sensor_id']]['arrive_time_first'] = $temp_first_time;
                    $temp_first_distance                                     = $this->match_turns_rounds_info['ma_distance'];
                    //设置终点时间
                    $this->match_first_zhong_limit = $temp_first_time + $this->match_zhong_limit;
                } else {
                    $dvalue                                                  = $this->temp_record[$v['sensor_id']]['arrive_time'] - $temp_first_time;
                    $this->temp_record[$v['sensor_id']]['arrive_time_first'] = "+" . $dvalue;
                }
            }
            $next_rank   = count($match_rank) + 1;
            $match_rank2 = Db::table('up__match_yacht_record')
                ->where(['match_turns_rounds_id' => $match_turns_rounds_id])
                ->where('type', '=', '1')
                ->order('distance desc')->select();
            foreach ($match_rank2 as $k => $v) {
                if ($next_rank == 1) {
                    $temp_first_distance = $this->temp_record[$v['sensor_id']]['distance'];
                }
                $this->temp_record[$v['sensor_id']]['ranking']    = $next_rank;
                $this->temp_record[$v['sensor_id']]['temp_score'] = $next_rank;
                $next_rank++;
            }
            //距第一名距离，和前一名距离并循环更新到record表
            foreach ($this->temp_record as $k => $v) {
                $this->temp_record[$k]['time'] = $time;
                if ($v['ranking'] == 1) {
                    $this->temp_record[$k]['to_first_distance'] = 0;
                } else {
                    $this->temp_record[$k]['to_first_distance'] = $temp_first_distance - $this->temp_record[$k]['distance'];
                }

                Db::table('up__match_yacht_record')->where('id', $v['id'])->update($this->temp_record[$k]);
            }
        }


        //$step_data[1] = $boat_to_calculate;
//        $result = Db::table('up__match_yacht_record')
//            ->where('match_turns_rounds_id', $match_turns_rounds_id)->field('sensor_id,user_id,speed,time,
//        distance,to_first_distance,five_hundred_time,five_hundred_consuming,track_num,arrive_time,accumulated_time,arrive_time_first,
//        type,ranking,temp_score,lat,lon,average_fh_start_time,average_speed')
//            ->select();
        //生成数据快照
        Db::table('up__match_datas_yacht')->insert([
            'match_turns_rounds_id' => $match_turns_rounds_id,
            'time'                  => $time,
            'data'                  => json_encode(array_values($this->temp_record))
        ]);

        $this->redis->set('up__match_datas_yacht', json_encode($this->temp_record));
        $this->temp_record_last = $this->temp_record;

        //判断时间是否超过终止时间
        //if ($this->match_first_zhong_limit != 0) {
        $flag = 0;//变为1则还有船未完成
        foreach ($this->temp_record as $key => $value) {
            if ($value['type'] == 1) {
                $flag = 1;
            }
        }
        if ($flag == 0) {
            Db::table("up__match_turns_rounds")->where('id', $match_turns_rounds_id)->update([
                'end_time' => microtime(true),
                'type'     => 2
            ]);
            $res_turns_rounds = Db::table("up__match_turns_rounds")->where('id', $match_turns_rounds_id)->find();
            $this->redis->set('up__match_turns_rounds_info', json_encode($res_turns_rounds));
            $this->redis->set('up__match_datas_yacht', '');
            $this->autoRise($this->match_turns_rounds_info['match_id']);
        }
        //}

        //dump($this->temp_record);
    }

    /**
     * 选手自动晋级下一轮
     */
    public function autoRise($match_id)
    {
        //选手自动晋级下一轮
        if ($this->match_info['match_saidao_num'] == 6) {
            //6赛道
            foreach ($this->temp_record as $k => $v) {
                $res = Db::table('match_rules_yacht')
                    ->where([
                        'track_num_all'     => $this->match_info['match_saidao_num'],
                        'player_num'        => count($this->temp_record),
                        'plan_num'          => $this->turns_rounds_info['plan_num'],
                        'turns_id'          => $this->turns_rounds_info['mt_id'],
                        'rounds_id'         => $this->turns_rounds_info['mr_id'],
                        'ranking'           => $v['ranking'],
                        'rules_categori_id' => 1
                    ])
                    ->find();
                if (!$res) {
                    $res = Db::table('match_rules_yacht')
                        ->where([
                            'track_num_all'     => $this->match_info['match_saidao_num'],
                            'player_num'        => count($this->temp_record),
                            'plan_num'          => 1,
                            'turns_id'          => $this->turns_rounds_info['mt_id'],
                            'rounds_id'         => $this->turns_rounds_info['mr_id'],
                            'ranking'           => $v['ranking'],
                            'rules_categori_id' => 1
                        ])
                        ->find();
                }
                Db::table('up_match_apply_info')
                    ->where(['ma_user_id' => $v['user_id']])
                    ->where(['ma_match_id' => $match_id])
                    ->update([
                        'track_num'    => $res['track_num'],
                        'ma_turns_id'  => $res['next_turns_id'],
                        'ma_rounds_id' => $res['next_rounds_id'],
                    ]);
                //更新用户所在组别
                $user_apply_info = Db::table('up_match_apply_info')
                    ->where(['ma_user_id' => $v['user_id']])
                    ->where(['ma_match_id' => $match_id])
                    ->find();
                $this->redis->set('ma_match_id' . $match_id . 'ma_user_id' . $v['user_id'], json_encode($user_apply_info));
            }
        } else {
            //4赛道
            //预赛组数
            $preliminary_num = ceil($this->turns_rounds_info['sign_up_num'] / 4);
            if ($this->turns_rounds_info['mr_id'] == $preliminary_num && $this->turns_rounds_info['mt_id'] == 1) {
                //如果是预赛且比完才有晋级
                $final_num   = 0;//决赛组数
                $sign_up_num = $this->turns_rounds_info['sign_up_num'];
                if ($sign_up_num % 4 == 0) {
                    $final_num = $preliminary_num;
                } else {
                    if ($sign_up_num % 2 != 0) {
                        $final_num = floor($sign_up_num / 6) + 1;
                    } else {
                        $final_num = floor($sign_up_num / 4);
                    }
                }
                //赛道数组
                $track_num = [2, 3, 1, 4];

                $group_num = ceil($sign_up_num / 4);
                //查询所有参加预赛的运动员
                $first_rounds_turns = $this->turns_rounds_info['id'] + 1 - $preliminary_num;
                $final_user         = Db::table('up__match_yacht_record')
                    ->where('match_turns_rounds_id', '>=', $first_rounds_turns)
                    ->where('match_turns_rounds_id', '<=', $this->turns_rounds_info['id'])
                    ->order('accumulated_time asc')
                    ->select();
                //临时存放各小组数据
                $data = [];
                foreach ($final_user as $k => $v) {
                    array_push($data, $v);
                    if (count($data) == 4 || $k == (count($final_user) - 1)) {
                        $ma_rounds_id = ceil($k / 4);
                        if ($ma_rounds_id == 0) {
                            $ma_rounds_id = 1;
                        }
                        foreach ($data as $key => $value) {
                            Db::table('up_match_apply_info')
                                ->where(['ma_user_id' => $value['user_id']])
                                ->where(['ma_match_id' => $match_id])
                                ->update([
                                    'ma_turns_id'  => 5,
                                    'ma_rounds_id' => $ma_rounds_id,
                                    'ma_dao_num'   => $track_num[$key],
                                ]);
                            //更新用户所在组别
                            $user_apply_info = Db::table('up_match_apply_info')
                                ->where(['ma_user_id' => $value['user_id']])
                                ->where(['ma_match_id' => $match_id])
                                ->find();
                            $this->redis->set('ma_match_id' . $match_id . 'ma_user_id' . $value['user_id'], json_encode($user_apply_info));
                        }
                        $data = [];
                    } else {
                        continue;
                    }
                }
            }
        }

    }

    /**
     * 获取实时竞赛数据
     * @param $match_id '比赛id'
     * @param $match_turns_rounds_id '比赛轮次id'
     * @return {app_sb_id,app_id,app_number,app_ercode}
     */
    public function getLiveDatas()
    {
        $data['match_turns_rounds_id'] = input('match_turns_rounds_id');
        $data['match_id']              = input('match_id');
        $m_d_id                        = '';
        if (!$data['match_turns_rounds_id']) {
            if (!$data['match_id']) {
                return json(array('status' => 100, 'msg' => "参数不能同时为空！"));
            } else {
                $m_d_id = Db::table('up__match_turns_rounds')->where(['match_id' => $data['match_id'], 'type' => 1])->value('id');
                if (!$m_d_id) {
                    // $m_d_id = Db::table('up__match_turns_rounds')->where(['match_id' => $data['match_id'], 'type' => 0])->value('id');
                    // if (!$m_d_id) {
                    return json(array('status' => 100, 'msg' => '没有进行中的赛次'));
                    // }
                }
            }
        } else {
            $m_d_id = $data['match_turns_rounds_id'];
        }
        $match_turns         = Db::table('up__match_turns_rounds')->where(['id' => $m_d_id])->find();
        $time                = time();
        $time_scope          = $time - 5;
        $boat_calculate_data = [];
        $boat_calculate_data = array_values(json_decode($this->redis->get('up__match_datas_yacht'), true));
        if ($boat_calculate_data == NULL || $boat_calculate_data == "" || $boat_calculate_data == []) {
            $sensors_id = Db::table('up__match_yacht_record')->where('match_turns_rounds_id', '=', $m_d_id)->select();
            if ($sensors_id == []) {
                //去match_info表查询相关选手
                $user_list = Db::table('up_match_apply_info')->where([
                    'ma_match_id'   => $match_turns['match_id'],
                    'ma_group'      => $match_turns['ma_group'],
                    'ma_boat_type'  => $match_turns['ma_boat_type'],
                    'ma_distance'   => $match_turns['ma_distance'],
                    'ma_turns_id'   => $match_turns['mt_id'],
                    'ma_rounds_id'  => $match_turns['mr_id'],
                    'ma_match_cate' => 2,
                    'ma_role'       => 1,
                    //'ma_baodao_status'=>2
                ])->field("ma_user_id as user_id,concat('boat_',`ma_user_id`) as sensor_id,ma_dao_num as track_num")->select();
                if (count($user_list) == 0) {
                    throw new Exception('请先对要进行比赛的用户进行分组,抽签', 4);
                }
                $rank = 1;
                foreach ($user_list as $k => $v) {
                    $temp = [
                        //帆船参数计算结果
                        "sensor_id"              => $v['sensor_id'], //设备id
                        "user_id"                => $v['user_id'],
                        "ranking"                => $k + 1, //排名
                        "temp_score"             => $k + 1, //排名
                        "distance"               => 0, //已行进距离
                        "speed"                  => 0, //速度
                        "arrive_time"            => 0, //
                        "accumulated_time"       => 0,//累计用时
                        "track_num"              => $v['track_num'], //赛道
                        "arrive_time_first"      => 0, //到达时间
                        "to_first_distance"      => 0, //距第一名距离
                        "five_hundred_time"      => 0, //到达500米时间
                        "five_hundred_consuming" => 0,//500米用了多久时间
                        'average_fh_start_time'  => $time,
                        'average_speed'          => 0,
                    ];
                    array_push($boat_calculate_data, $temp);
                }
            }
        } //else {
        //  $boat_calculate_data = json_decode($boat_calculate_data, true);
        //}
        //$location_data = Db::table('up__match_step_yacht')->where(['match_turns_rounds_id' => $m_d_id, 'time' => $time])->value('data');
        //$location_data = json_decode($location_data, true);
        /*//比赛之前没有快照则从原始表获取数据
        if ((is_array($location_data) && count($location_data) == 0) || $location_data == '' || $location_data == null) {
            $time_pre   = $time - 1;
            $sensors_id = Db::table('up__sensor_device')->where('match_detail_id', $m_d_id)->column('sensor_id');

            $location_data = Db::table('up__match_origin')
                ->distinct('sensor_id')
                ->where('create_time', '>', $time_pre)
                ->where('create_time', '<=', $time)
                ->where('sensor_id', 'in', $sensors_id)
                ->order('id desc')
                ->column('sensor_id,lat,lon');
        } else {
            $location_data = array_merge($location_data[1], $location_data[2]);
        }*/

        $data = [
            "match_turns_rounds_id" => $m_d_id, //比赛轮次id
            "time"                  => $time, // 时间戳
            "boat_calculate_data"   => $boat_calculate_data, //船只参数计算结果
            "match_turns_data"      => $match_turns
        ];
        return json(array('status' => 200, 'msg' => $data));

    }


    /**
     * 距离计算
     * @param $point1 浮标位置、船位置
     * @param $point2
     * $point1:[lat=>11,lon=>22]
     */
    public function getDistance($point1, $point2)
    {
        // 将角度转为弧度
        $radLat1  = deg2rad((float)$point1['lat']); //deg2rad()函数将角度转换为弧度
        $radLat2  = deg2rad((float)$point2['lat']);
        $radLng1  = deg2rad((float)$point1['lon']);
        $radLng2  = deg2rad((float)$point2['lon']);
        $a        = $radLat1 - $radLat2;
        $b        = $radLng1 - $radLng2;
        $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $distance;
    }

    //----------------------------回放-------------------------------

    /**
     * 获取比赛下面所有的赛次
     * @param $match_id
     * @return
     */
    public function getMatchTurnsList()
    {
        try {
            $match_id = input('match_id');
            if (!$match_id) {
                return json(array('status' => 100, 'msg' => '参数不能为空'));
            }
            $detail_info = Db::table('up__match_turns_rounds d')
                ->join('up_match_group g', 'g.mg_id=d.ma_group', "LEFT")
                ->join('up__match_turns t', 't.mt_id=d.mt_id', "LEFT")
                ->join('up__match_rounds r', 'r.mr_id=d.mr_id', "LEFT")
                ->where(['d.match_id' => $match_id])
                ->where(['d.type' => 2])
                ->field('d.id,d.match_id,t.mt_name as turn_name,r.mr_name as round_name,
                g.mg_name as level_name,d.ma_boat_type,d.ma_distance,d.start_time,d.end_time')->select();
            return json(array('status' => 200, 'msg' => 'success', 'data' => $detail_info));
        } catch (\Exception $e) {
            return json(array('status' => 100, 'msg' => $e->getMessage()));
        }
    }

    /**
     * 获取回放初始化参数
     * @param $match_turns_rounds_id
     * @return
     */
    public function initPlayBack()
    {
        try {
            $match_turns_rounds_id = input('match_turns_rounds_id');
            if (!$match_turns_rounds_id) {
                return json(array('status' => 100, 'msg' => '参数不能为空'));
            }
            $data['turns_rounds_info'] = Db::table('up__match_turns_rounds d')
                ->join('up_match_group g', 'g.mg_id=d.ma_group', "LEFT")
                ->join('up__match_turns t', 't.mt_id=d.mt_id', "LEFT")
                ->join('up__match_rounds r', 'r.mr_id=d.mr_id', "LEFT")
                ->where(['d.id' => $match_turns_rounds_id])
                //->where(['d.type' => 2])
                ->field('d.*,t.mt_name as turn_name,r.mr_name as round_name,
                g.mg_name as level_name')->find();


            $data['device_info'] = Db::table('up__match_yacht_record r')
                ->join('up_match_apply_info i', 'r.user_id=i.ma_user_id', "LEFT")
                ->join('up_club c', 'c.club_id=i.ma_club_id', "LEFT")
                ->where(['r.match_turns_rounds_id' => $match_turns_rounds_id])
                ->field('r.user_id,r.sensor_id,i.ma_dao_num as track_num,i.ma_team_name,
                c.club_name,c.club_image,i.ma_color as color')->select();

            //$data['match_data'] = Db::table('up_match')->where('match_id', $data['turns_rounds_info']['match_id'])->find();

            return json(array('status' => 200, 'msg' => 'success', 'data' => $data));
        } catch (\Exception $e) {
            return json(array('status' => 100, 'msg' => $e->getMessage()));
        }
    }

    /**
     * 获取回放初始化参数
     * @param $match_turns_rounds_id
     * @return
     */
    public function getPlayBackDatas()
    {
        try {
            $match_turns_rounds_id = input('match_turns_rounds_id');
            if (!$match_turns_rounds_id) {
                return json(array('status' => 100, 'msg' => '参数不能为空'));
            }
            $turns_rounds_info = Db::table('up__match_turns_rounds d')
                ->where(['d.id' => $match_turns_rounds_id])
                //->where(['d.type' => 2])
                ->field('d.*')->find();
            if (!$turns_rounds_info) {
                return json(array('status' => 100, 'msg' => '没有该轮次比赛'));
            }
            $end_time = time();
            //5分钟后开始
            $start_time = $turns_rounds_info['start_time'] + $this->temp_all_countdown;
            if ($turns_rounds_info['type'] == 2) {
                $end_time = $turns_rounds_info['end_time'];
            }

            $data = Db::table('up__match_datas_yacht r')
                ->where(['r.match_turns_rounds_id' => $match_turns_rounds_id])
                ->where('r.time', '>=', $start_time)
                ->where('r.time', '<=', $end_time)
                ->field('time,data')->select();


            foreach ($data as $i => $item) {
                $data[$i]['data'] = json_decode($item['data'], true);
            }

            return json(array('status' => 200, 'msg' => 'success', 'data' => $data));
        } catch (\Exception $e) {
            return json(array('status' => 100, 'msg' => $e->getMessage()));
        }
    }

    /**
     * 获取比赛所有组别
     * @param $match_id 比赛轮次id
     * @return success
     */
    public function getAllLevels()
    {
        try {
            $match_id = input('match_id');
            if (!$match_id) {
                return json(array('status' => 100, 'msg' => '比赛id不能为空'));
            }
            $match_info = Db::table('up_match')
                ->where('match_id', $match_id)
                ->where('match_init', 2)->find();
            if (!$match_info) {
                return json(array('status' => 100, 'msg' => '该比赛还未开始'));
            }
            $data = $this->_match_info($match_id);
            return json(array('status' => 200, 'msg' => 'success', 'data' => $data));
        } catch (\Exception $e) {
            return json(array('status' => 100, 'msg' => $e->getMessage() . '行：' . $e->getLine()));
        }

    }

    /**
     * 获取比赛临时成绩
     * @param $match_id 比赛轮次id
     * @param $mg_id 比赛组别id
     * @param $ma_boat_type 比赛船型
     * @param $ma_distance 赛道距离
     * @return success
     */
    public function getTempScore()
    {
        try {

            $match_id = input('match_id');
            if (!$match_id) {
                return json(array('status' => 100, 'msg' => '比赛id不能为空'));
            }

            $data = input('sets');
            $data = json_decode($data, true);

            if (!key_exists('group_type', $data)) {
                return json(array('status' => 100, 'msg' => '组别类型不能为空'));
            }
            if (!key_exists('turn', $data)) {
                return json(array('status' => 100, 'msg' => '轮次不能为空'));
            }
            if (!key_exists('round', $data)) {
                return json(array('status' => 100, 'msg' => '组次不能为空'));
            }
            if (!key_exists('yacht_type', $data)) {
                return json(array('status' => 100, 'msg' => '赛艇类型不能为空'));
            }
            if (!key_exists('race_distance', $data)) {
                return json(array('status' => 100, 'msg' => '赛道长度不能为空'));
            }

            // 比赛包含的赛事组别信息
            $data_new['turns_rounds_info'] = Db::table('up__match_turns_rounds')
                ->where('match_id', $match_id)
                ->where('ma_group', $data['group_type'])
                ->where('ma_boat_type', $data['yacht_type'])
                ->where('ma_distance', $data['race_distance'])
                ->where('mr_id', $data['round'])
                ->where('mt_id', $data['turn'])
                ->where('type', 2)
                ->find();

            if (!is_array($data_new['turns_rounds_info'])) {
                return json(array('status' => 100, 'msg' => "该赛次比赛不存在或者还未结束"));
            } else {
                //去match_info表查询相关选手
                $temp_score_arr = Db::table('up__match_yacht_record')
                    ->alias('yr')
                    ->join('up__match_turns_rounds tr', 'tr.id = yr.match_turns_rounds_id')
                    ->join("up_match_apply_info ai", "ai.ma_user_id = yr.user_id ", 'LEFT')
                    ->join("up_u_user u", "u.user_id = ai.ma_user_id ", 'LEFT')
                    ->where('yr.match_turns_rounds_id', $data_new['turns_rounds_info']['id'])
                    ->where('ai.ma_role', 1)
                    ->field('u.user_id,u.user_username,u.user_gender,yr.track_num,ai.ma_team_name,yr.temp_score as placing,accumulated_time')
                    ->order('mr_id asc,temp_score asc')
                    ->select();
                foreach ($temp_score_arr as $k => $v) {
                    $temp_score_arr[$k]['team_member'] = Db::table('up_match_apply_info')
                        ->alias('ai')
                        ->join('up_u_user u', "u.user_id = ai.ma_user_id ", 'LEFT')
                        ->where(['ai.ma_team_name' => $v['ma_team_name']])->column('u.user_username');
                }
            }
            return json(array('status' => 200, 'msg' => 'success', 'data' => $temp_score_arr));
        } catch (\Exception $e) {
            return json(array('status' => 100, 'msg' => $e->getMessage() . '行：' . $e->getLine()));
        }
    }

    /**
     * 抽签后初始化初赛
     * @param $match_id 比赛id
     * @param $ma_group 组别id
     * @param $ma_boat_type 船型
     * @param $ma_distance 距离
     * @return success
     */
    public function initYacht($match_id, $ma_group, $ma_boat_type, $ma_distance)
    {
        try {
            $match_turns_info['ma_match_id']   = $match_id;
            $match_turns_info['ma_group']      = $ma_group;
            $match_turns_info['ma_boat_type']  = $ma_boat_type;
            $match_turns_info['ma_distance']   = $ma_distance;
            $match_turns_info['ma_match_cate'] = 2;
            $match_turns_info['ma_role']       = 1;
            $user_apply_info                   = Db::table('up_match_apply_info')
                ->where($match_turns_info)
                ->order('ma_lots asc')
                ->select();
            if (count($user_apply_info) < 1) {
                return array('status' => 100, 'msg' => '没有相关队员');
            }
            if ($user_apply_info[0]['ma_turns_id']) {
                return array('status' => 100, 'msg' => '该组队员已经抽签完毕，请勿重复抽签');
            }

            $match_info       = Db::table('up_match')->where(['match_id' => $match_turns_info['ma_match_id']])->find();
            $match_saidao_num = $match_info['match_saidao_num'];
            $num              = count($user_apply_info);//参加比赛人员个数
            //dump($num);die;
            //赛道数组
            $track_num = [3, 4, 2, 5, 1, 6];
            if ($match_saidao_num == 6) {
                //赛道数组
                $track_num = [3, 4, 2, 5, 1, 6];
            } else {
                //赛道为4
                //赛道数组
                $track_num = [2, 3, 1, 4];
            }
            $group_num         = ceil($num / $match_saidao_num);
            $average_group_num = 0;
            if ($num % 2 == 0) {
                $average_group_num = $num / $group_num;
            } else {
                $average_group_num = ($num + 1) / $group_num;
            }
            //临时存放各小组数据
            $data = [];
            foreach ($user_apply_info as $k => $v) {
                if (count($data) == $average_group_num || $k == ($num - 1)) {
                    $ma_rounds_id = ceil($k / $average_group_num);
                    array_push($data, $v);
                    if ($ma_rounds_id == 0) {
                        $ma_rounds_id = 1;
                    }
                    foreach ($data as $key => $value) {
                        Db::table('up_match_apply_info')
                            ->where(['ma_id' => $value['ma_id']])
                            ->update([
                                'ma_turns_id'  => 1,
                                'ma_rounds_id' => $ma_rounds_id,
                                'ma_dao_num'   => $track_num[$key],
                            ]);
                        //更新用户所在组别
                        $user_info = Db::table('up_match_apply_info')
                            ->where(['ma_id' => $value['ma_id']])
                            ->find();
                        $this->redis->set('ma_match_id' . $match_id . 'ma_user_id' . $value['ma_user_id'], json_encode($user_info));

                    }
                    $data = [];
                } else {
                    array_push($data, $v);
                    continue;
                }
            }
            return array('status' => 200, 'msg' => 'success');
        } catch (\Exception $e) {
            return array('status' => 100, 'msg' => $e->getMessage() . '行：' . $e->getLine());
        }
    }

    /**
     * 添加比赛晋级规则
     * @param $track_num_all 赛道数
     * @param $player_num 比赛总人数
     * @param $plan_num 下一轮选择的方案复赛、半决赛等方案1、2、3（当有多种比赛方案选择时有效，否则默认1）',
     * @param $turns_id 当前所在轮次id 比如在初赛id为1，请看up__match_turns表
     * @param $rounds_id 当前所在组别id 比如在第一组则id为1，请看up__match_rounds表
     * @param $ranking 本轮名次
     * @param $track_num 选手下一轮所属赛道
     * @param $next_turns_id 选手下一轮所属轮次id
     * @param $next_rounds_id 选手下一轮所属组次id
     * @return success
     */
    public function addYachtRules()
    {
        /*`track_num_all` tinyint(2) DEFAULT NULL COMMENT '赛道数',
  `player_num` int(5) DEFAULT NULL COMMENT '选手数量',
  `plan_num` tinyint(2) DEFAULT NULL COMMENT '复赛、半决赛等方案1 2 3（当有多种比赛方案选择时有效，否则默认1）',
  `turns_id` int(2) DEFAULT NULL COMMENT '轮次id',
  `rounds_id` int(3) DEFAULT NULL COMMENT '组次id',
  `ranking` tinyint(3) DEFAULT NULL COMMENT '名次',
  `track_num` tinyint(2) DEFAULT NULL COMMENT '选手下一轮所属赛道',
  `next_turns_id` int(2) DEFAULT NULL COMMENT '选手下一轮所属轮次id',
  `next_rounds_id` int(3) DEFAULT NULL COMMENT '选手下一轮所属组次id',
  `rules_categori_id` int(10) DEFAULT '1' COMMENT '赛艇晋级规则种类id，默认1是默*/
        $data = [
            'track_num_all'     => input('track_num_all'),
            'player_num'        => input('player_num'),
            'plan_num'          => input('plan_num'),
            'turns_id'          => input('turns_id'),
            'rounds_id'         => input('rounds_id'),
            'ranking'           => input('ranking'),
            'track_num'         => input('track_num'),
            'next_turns_id'     => input('next_turns_id'),
            'next_rounds_id'    => input('next_rounds_id'),
            'rules_categori_id' => 1
        ];
        foreach ($data as $k => $v) {
            if (!$v) {
                return json(array('status' => 100, 'msg' => $k . '字段不能为空'));
            }
        }
        $res = Db::table('up__rules_yacht')->where($data)->find();
        if ($res) {
            return json(array('status' => 100, 'msg' => '该规则已经存在'));
        }
        Db::table('up__rules_yacht')->insert($data);
        return json(array('status' => 200, 'msg' => 'success'));
    }
}